﻿jQuery.fn.pagination = function(maxentries, opts) {
    opts = jQuery.extend({
        items_per_page: 10,
        num_display_entries: 10,
        current_page: 0,
        num_edge_entries: 0,
        link_to: "#",
        prev_text: "3",
        next_text: "4",
        ellipse_text: "...",
        lang: 'zh-cn',
        prev_show_always: true,
        next_show_always: true,
        callback: function() { return false; }
    }, opts || {});

    return this.each(function() {
        function numPages() {
            return Math.ceil(maxentries / opts.items_per_page);
        }
        function getInterval() {
            var ne_half = Math.ceil(opts.num_display_entries / 2);
            var np = numPages();
            var upper_limit = np - opts.num_display_entries;
            var start = current_page > ne_half ? Math.max(Math.min(current_page - ne_half, upper_limit), 0) : 0;
            var end = current_page > ne_half ? Math.min(current_page + ne_half, np) : Math.min(opts.num_display_entries, np);
            return [start, end];
        }
        function pageSelected(page_id, evt) {
            current_page = page_id;
            drawLinks();
            var continuePropagation = opts.callback(page_id, panel);
            if (!continuePropagation) {
                if (evt.stopPropagation) {
                    evt.stopPropagation();
                }
                else {
                    evt.cancelBubble = true;
                }
            }
            return continuePropagation;
        }
        function drawLinks() {
            var i = 0;
            var lang = opts.lang;
            panel.empty();
            var interval = getInterval();
            var np = numPages();
            var getClickHandler = function(page_id) {
                return function(evt) { return pageSelected(page_id, evt); };
            };

            if (maxentries > 0) {
                jQuery("<div class='DivFloatLeft' style='line-height:24px;width:49%;float:left;text-align:right;'>当前 " + (parseInt(current_page, 10) + 1) + " / " + np + " 页 | 共有 " + maxentries + " 记录</div><div class='DivFloatRight' id='DivFloatRight'  style='line-height:20px;height:20px;width:49%;float:left;text-align:left;'></div>").appendTo(panel);
            }
            else {

                jQuery("<span >&lt;没有相关记录&gt;</span>").appendTo(panel);
            }
            var appendItem = function(page_id, appendopts) {
                if (page_id != -1) {
                    page_id = page_id < 0 ? 0 : (page_id < np ? page_id : np - 1);
                    appendopts = jQuery.extend({ text: page_id + 1, classes: "" }, appendopts || {});
                    var lnk;
                    if (page_id == current_page) {
                        lnk = jQuery("<span class='current'>" + (appendopts.text) + "</span>");
                    } else {
                        lnk = jQuery("<a>" + (appendopts.text) + "</a>")
						.bind("click", getClickHandler(page_id))
						.attr('href', opts.link_to.replace(/__id__/, page_id));
                    }
                    if (appendopts.classes) { lnk.addClass(appendopts.classes); }
                    jQuery("#DivFloatRight").append(lnk);

                }
                else {
                    jQuery("#DivFloatRight").append(jQuery("<span>转到第</span><input class='TextBox01' id='iPage' name='iPage' maxLength='2' size='2' type='text' />页"
                   + "<input type='button' id='iGo' name='iGo' value='跳转'   class='Button01' />"));
                    $("#iGo").bind("click", checkPageNum);
                }
            };
            var checkPageNum = function() {
                var inp = document.getElementById('iPage');
                var txt = inp.value;
                try {

                    var v = __str2int(txt);

                    if (v >= 0) {
                        if (v > 0 && v <= np) {
                            inp.value = v;
                            pSCb(v - 1, null);
                            return true;
                        }

                    }
                } catch (e) { }
                alert('页码错误！');
                return false;
            };
            if (np > 0) {
                appendItem(0, { text: "9", classes: "" });
            }

            if (opts.prev_text && (current_page > 0 && opts.prev_show_always)) {
                appendItem(current_page - 1, { text: opts.prev_text, classes: "prev" });
            }

            if (interval[0] > 0 && opts.num_edge_entries > 0) {
                var end = Math.min(opts.num_edge_entries, interval[0]);
                for (i = 0; i < end; i++) {
                    //   appendItem(i);
                }
                if (opts.num_edge_entries < interval[0] && opts.ellipse_text) {
                    // jQuery("<span>" + opts.ellipse_text + "</span>").appendTo(panel);
                }
            }
            for (i = interval[0]; i < interval[1]; i++) {
                //  appendItem(i);
            }
            if (interval[1] < np && opts.num_edge_entries > 0) {
                if (np - opts.num_edge_entries > interval[1] && opts.ellipse_text) {
                    //  jQuery("<span>" + opts.ellipse_text + "</span>").appendTo(panel);
                }
                var begin = Math.max(np - opts.num_edge_entries, interval[1]);
                for (i = begin; i < np; i++) {
                    // appendItem(i);
                }
            }
            if (opts.next_text && (current_page < np - 1 && opts.next_show_always)) {
                appendItem( parseInt( current_page) + 1, { text: opts.next_text, classes: "next" });
            }
            if (np > 0) {
                if (np > 0) {
                    appendItem(np - 1, { text: ":", classes: "" });
                }
            }
            appendItem(-1, { text: "", classes: "" });
        }
        var current_page = opts.current_page;
        maxentries = (!maxentries || maxentries < 0) ? 0 : maxentries;
        opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0) ? 1 : opts.items_per_page;
        var panel = jQuery(this);
        this.selectPage = function(page_id) { pageSelected(page_id); };
        this.prevPage = function() {
            if (current_page > 0) {
                pageSelected(current_page - 1);
                return true;
            }
            else {
                return false;
            }
        };
        this.nextPage = function() {
            
            if (current_page < numPages() - 1) {
                pageSelected(current_page + 1);
                return true;
            }
            else {
                return false;
            }
        };
        drawLinks();
    });
};

function __str2int(txt) {
    var st1 = '０１２３４５６７８９0123456789';
    var result = 0;

    for (i = 0; i < txt.length; i++) {
        var iv = txt.substring(i, i + 1);
        var v = st1.indexOf(iv) % 10;
        if (v < 0) return -1;
        result = result * 10 + v;
    }
    return result;
}
